<?php
namespace app\staff\controller;

use think\Request;
use think\Db;
use think\Session;
use think\Controller;
use think\Config;
use Godok\Org\Auth;
use think\Log;

class Order extends Controller
{
	//订单列表
	function index(){
		$user_id = Request()->param('user_id');
		$list = Db::name('order')->where("order_status > -1 and user_id={$user_id}")->field(['order_id,create_time,order_status,order_money,shipping_money'])->order('create_time desc')->select();

		foreach ($list as $key => $value) {
			$list[$key]['list'] = Db::name('order_goods')->field(['goods_name,goods_id,goods_picture'])->where('order_id',$value['order_id'])->select();
			$data[$key]['num'] = Db::name('order_goods')->where('order_id',$value['order_id'])->count('order_id');

		}
		$this->success('success','',$list);
	}

	//订单详情
	function detailOrder(){
		$order_id = Request()->param('order_id');
		$data = Db::name('order')->field(['order_no,goods_money,order_money,shipping_money,receiver_name,receiver_pcd,receiver_address,remarks'])->where('order_id',$order_id)->find();
		$data['list'] = Db::name('order_goods')->field(['brand_name,goods_name,goods_picture,price,goods_spec_name,goods_specval_name,num'])->where('order_id',$order_id)->select();
		foreach ($data['list'] as $key => $value) {
			$data['list'][$key]['price_all'] = $value['price']*$value['num'];
		}
		$this->success('success','',$data);
	}

	//提交订单
	function order(){
		$user_id = Request()->param('user_id');
		$agent_id = Request()->param('agent_id');
		$address_id = Request()->param('address_id');
		$remarks = Request()->param('remarks');

		if($goods_money >= Config::get('sites.free_delivery_fee')){
			$shipping_money = 0;
		}else{
			$shipping_money = Config::get('sites.delivery_fee');
		}

		$list = json_decode(Request()->param('list'),true);

		$user = Db::name('user')->field(['realname,openid'])->where('id',$user_id)->find();

		$employee = Db::name('employee')->field(['name'])->where('id',$agent_id)->find();

		$address = Db::name('user_address')->field(['name,pcd,address,phone'])->where('address_id',$address_id)->find();

		foreach ($list as $key => $value) {
			$goods[] = Db::table('sdzx_goods_specval')->alias('gs')
			->field('g.goods_name,g.goods_id,gs.spec_id,gs.spec_name,gs.specval_id,gs.specval_name,s.supplier_name,s.supplier_id,gs.price,g.picture,g.brand_id,g.brand_name')
			->join('sdzx_goods g','g.goods_id=gs.goods_id')
			->join('sdzx_supplier s','s.supplier_id=gs.supplier_id','left')
			->where('gs.specval_id',$value['specval_id'])
			->find();

			$cart[] = $value['specval_id'];
		}
		//计算商品总价
		$goods_money = 0;			
		$order_money = 0;
		foreach ($goods as $key => $value) {
			$goods_money += $value['price']*$list[$key]['num'];
		}
		$order_money += $goods_money;
		$order_money += $shipping_money; //订单总价

		if (Config::get('sites.scheduling')) {
            $scheduling_time = strtotime(Config::get('sites.scheduling'));
            if (time()<=$scheduling_time) {
                $data['scheduling'] = date('Y-m-d');
            } else {
                $data['scheduling'] = date('Y-m-d', strtotime('+1 day'));
            }
        } else {
            $data['scheduling'] = date('Y-m-d');
        }
		$data = [
			'order_no' => self::orderSn($user_id),
			'order_type' => 2,		//订单类型1：自主下单 2：代下单
			'payment_type' => 1,		//支付类型1：自主支付 2：管家支付
			'user_id' => $user_id,
			'user_name' => $user['realname'],
			'openid'	=> $user['openid'],
			'agent_id'	=> $agent_id,
			'agent_name'	=> $employee['name'],
			'create_time'	=> date('Y-m-d H:i:s'),
			'receiver_name'	=> $address['name'],
			'receiver_mobile'	=> $address['phone'],
			'receiver_pcd'	=> $address['pcd'],
			'receiver_address' => $address['address'],
			'goods_money' 	=> $goods_money,
			'order_money'	=> $order_money,
			'coupon_money' => 0,
			'coupon_id' => 0,
			'user_money' => 0,
			'shipping_money' => $shipping_money,
			'remarks'	=> $remarks
		];
		Db::startTrans();

		$res = Db::name('order')->insertGetId($data);
		if(!$res){
			Db::rollback();
			$this->error('订单保存失败');
		}

		foreach ($goods as $key => $value) {
			$obj[] = [
				'order_id' => $res,
				'goods_name' => $value['goods_name'],
				'goods_id' => $value['goods_id'],
				'goods_spec_id' => $value['spec_id'],
				'goods_spec_name' => $value['spec_name'],
				'goods_specval_id' => $value['specval_id'],
				'goods_specval_name' => $value['specval_name'],
				'supplier_name' => $value['supplier_name'],
				'supplier_id' => $value['supplier_id'],
				'price' => $value['price'],
				'num' => $list[$key]['num'],
				'goods_picture' => $value['picture'],
				'brand_id' => $value['brand_id'],
				'brand_name' => $value['brand_name']
			];
		}
		$re = Db::name('order_goods')->insertAll($obj);

		if(!$re){
			Db::rollback();
			$this->error('订单保存失败');
		}

        Db::name('order_action')->insert([
            'user_id'          => $user_id,
            'order_id'         => $res,
            'act_time'         => date('Y-m-d H:i:s'),
            'order_status'     => 0,
            'bop_order_status' => 0
        ]);
        // 清除购物车数据
        Db::name('user_cart')->where(['specval_id'=>['in',$cart],'user_id'=>$user_id])->delete();
        Db::commit();
        $this->success('下单成功');
	}


	/**
     * 生成订单号
     * @return [type] [description]
     */
    function orderSn($obj)
    {
        $u = strrev(sprintf('%04s', substr($obj, -4)));
        $sn = $u.date('ymdHi').sprintf('%02s', rand(0, 99));
        return $sn;
    }

    /**
    * 获取用户订单运费  之后可能跟用户等级有关
    * @return [type] [description]
    */
    public function shippingMoney()
    {	
    	$goods_money = Request()->param('goods_money');
    	$user_id = Request()->param('user_id');
        $free_shipping = Db::field('ul.free_shipping')
        ->table('sdzx_shop')->alias('s')
        ->join('sdzx_user_level ul','s.level=ul.level_id','left')
        ->where("s.user_id={$user_id}")
        ->value('free_shipping');

        $return_arr = [
            'delivery_fee' => Config::get('sites.delivery_fee')?:0,
            'free_delivery_fee' => Config::get('sites.free_delivery_fee')?:0
        ];

        if ($free_shipping) {
            $return_arr['delivery_fee'] = 0;
        }else if ($goods_money>0 && $return_arr['free_delivery_fee']>0 && $goods_money>=$return_arr['free_delivery_fee']) {
            $return_arr['delivery_fee'] = 0;
        }
        $this->success('success','',$return_arr);
    }
}


